library(quantmod)
library(ggplot2)
library(scales)

sp500 <- new.env()

setSymbolLookup(BN=list(name='000009.SZ',src='yahoo'))
getSymbols("BN",from = as.Date("2019-01-01"), to = as.Date("2019-12-27"))
BN = Cl(BN)

MA <- function(data, mas=c(5, 10, 30)) 
{
  ma_data <- data
  for(m in mas) 
  {
    ma_data <- merge(ma_data, EMA(data, m))
  }
  ma_data <- na.locf(ma_data, fromLast = TRUE)
  names(ma_data) <- c('Value', paste('MA', mas, sep=''))
  return(ma_data)
}

BNMA=MA(BN)
plot(BNMA)

getSignals<- function(data, mas_1=10, mas_2=30) 
{
  if(mas_1 == 0)
    ma_name_1 <- "Value"
  else
    ma_name_1 <- paste('MA', mas_1, sep='')
  
  ma_name_2 <- paste('MA', mas_2, sep='')
  ma_data <- data[, c("Value", ma_name_1, ma_name_2)] #please calculate ma value before and get a dataframe like the section above
  down_data <- ma_data[which(ma_data[, c(ma_name_1)] > ma_data[, c(ma_name_2)]), c("Value")]
  up_data <- ma_data[which(ma_data[, c(ma_name_1)] < ma_data[, c(ma_name_2)]), c("Value")]
  result <- merge(down_data, up_data)
  names(result) <- c("buy", "sell")
  result <- fortify(result, melt=TRUE)
  result<- result[-which(is.na(result$Value)),]
  signals <- result[order(result$Index),]
  signals$Signal <- ifelse(signals$Series == "buy", 1, 0)
  signals$Signal <- c(ifelse(signals$Series[1] == "buy", 1, -1),diff(signals$Signal))
  signals <- signals[which(signals$Signal != 0),]
  #delete odd rows
  if(nrow(signals)%%2 == 1) {
    if(signals$Series[1] == "buy")
      signals <- signals[-c(nrow(signals)),]
    else
      signals <- signals[-c(1),]
  }
  if(signals$Series[1] == "sell") {
    signals <- signals[-c(nrow(signals)),]
    signals <- signals[-c(1),]
  }
  return (signals)
}

signals = getSignals(BNMA)

# baseline收益率
baseMoney = as.numeric(BN[1])
baseReturn<-function(price)
{
  return ((price-baseMoney)/baseMoney)
}

# 策略收益率
startMoney=10
nowMoney=startMoney
holdShares=0
straReturn<-function(price)
{
  return (((holdShares*price)+nowMoney-startMoney)/startMoney)
}

allBaseLine=c()
allStra=c()
BNDate=index(BN)
BNPrice=coredata(BN)
for(i in 1:length(BN))
{
  date=as.character(BNDate[i])
  price=as.numeric(BNPrice[i])
  
  sub=which(signals$Index==date)
  if(length(sub)!=0)
  {
    if(signals$Signal[sub]==1) # 买入
    {
      holdShares=holdShares+1
      nowMoney=nowMoney-price
    }
    else
    {
      if(holdShares>0) 
      {
        holdShares=holdShares-1
        nowMoney=nowMoney+price
      }
    }
  }
  
  allBaseLine[date]=baseReturn(price)
  allStra[date]=straReturn(price)
}

ret=cbind(allBaseLine,allStra)
ret=as.xts(ret)
plot(ret)